#include "Change/textchange.h"

TextChange::TextChange(opType newOp, int newRev, int newUser, int newDoc, int newPos, int newNum, QString newData) :
		Change(newOp, newRev, newUser, newDoc, newPos)
{
	num = newNum;
	data = newData;
}

/**
  *	Construct a new TextChange from a QByteArray, which will store the message sent over the network
  */
TextChange::TextChange(QByteArray bytes)
{
	QDataStream sin(bytes);

	//get the operation
	quint8 op;
	sin >> op;
	operation = op;

	sin >> revisionId >> userId >> docId >> position;
	sin >> num;

	//get the char* data out
	if (operation == ADD_TEXT || operation == ADD_HTML)
	{
		char* newData = NULL;
		sin >> newData;
		data = QString(newData);
		delete [] newData;
	}

	//convert an ASCII control chars that we used back to unicode
	for (int i = 0; i < data.length(); i++)
	{
		if (data.at(i).toAscii() == (char)17)
		{
			qDebug("rec-convert1");
			data[i] = QChar(160);
		}
		else if (data.at(i).toAscii() == (char)18)
		{
			qDebug("rec-convert2");
			data[i] = QChar(8233);
		}
		else if (data.at(i).toAscii() == (char)19)
		{
			qDebug("rec-convert3");
			data[i] = QChar(8232);
		}
	}
}

/**
  *	Convert the TextChange into a QByteArray, for transmission over the network
  */
QByteArray TextChange::toBytes()
{
	QByteArray bytes;
	QDataStream sout(&bytes, QIODevice::WriteOnly);

	sout << operation << revisionId << userId << docId << position;
	sout << num;

	if (operation == ADD_TEXT || operation == ADD_HTML)
	{
		//we need to convert some unicode characters used by Qt into ASCII so they don't get lost...
		//we'll use some rare-sounding ASCII control characters:
		for (int i = 0; i < data.length(); i++)
		{			
			if (data.at(i).unicode() == 160)
			{
				qDebug("add-convert1");
				data[i] = QChar((char)17);
			}
			else if (data.at(i).unicode() == 8233)
			{
				qDebug("add-convert2");
				data[i] = QChar((char)18);
			}
			else if (data.at(i).unicode() == 8232)
			{
				qDebug("add-convert3");
				data[i] = QChar((char)19);
			}
		}

		sout << data.toAscii();
	}

	return bytes;
}
